package com.xiaoke.filter;

import com.alibaba.fastjson.JSON;
import com.xiaoke.domain.ResponseResult;
import com.xiaoke.domain.entity.LoginUser;
import com.xiaoke.utils.JwtUtil;
import com.xiaoke.utils.RedisCache;
import com.xiaoke.utils.WebUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

import static com.xiaoke.enums.AppHttpCodeEnum.NO_OPERATOR_AUTH;


@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Resource
    RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 获取 token
        String token = request.getHeader("Authorization");
        if(!StringUtils.hasText(token)) {
            //放行，让后面的过滤器执行
            filterChain.doFilter(request, response);
            return;
        }
        // 2解析token
        String userId;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userId = claims.getSubject();
        } catch (Exception e) {
            WebUtils.renderString(response,JSON.toJSONString(ResponseResult.errorResult(NO_OPERATOR_AUTH)));
            return;
        }

        //3获取userId, redis获取用户信息
        LoginUser loginUser = redisCache.getCacheObject("login:" + userId);
        if (Objects.isNull(loginUser)) {
            throw new RuntimeException("当前用户未登录！");
        }
//        //4封装Authentication
        UsernamePasswordAuthenticationToken authentication
                = new UsernamePasswordAuthenticationToken(loginUser, null,null);
//
//        //5存入SecurityContextHolder
        SecurityContextHolder.getContext().setAuthentication(authentication);
        //放行，让后面的过滤器执行
        filterChain.doFilter(request, response);
    }
}
